package tr.com.netgis;

import java.util.Date;

import tr.com.netgis.util.ReadWriteFileManager;
import tr.com.netgis.util.Utility;
import tr.com.netgis.web.SetLocationResponse;
import android.content.Context;

/**
 * 
 * @author NetGis
 *
 */
public class FileLogger {

	public static String logFileName = "NetMobileLocation.log";
	private static Object mutex = new Object();
	public static boolean DEBUG = false;
	
	public static boolean log(String log) {
		if (!DEBUG)
			return true;
		Context ctx = NGApplication.getAppContext();
		synchronized (mutex) {
			ReadWriteFileManager man = new ReadWriteFileManager();
			return man.writeToFile(ctx, (readLogContent(ctx) + "\r\n" + log.trim() + "\r\n").getBytes(), logFileName);			
		}
	}
	
	public static boolean log(Context ctx, SetLocationResponse response) {
		if (!DEBUG)
			return true;
		String log = response.toString();
		String now = Utility.createSimpleDateFormat().format(new Date());
		log = "---------\r\n" + now + "\r\n" + log + "\r\n---------";
		synchronized (mutex) {
			ReadWriteFileManager man = new ReadWriteFileManager();
			return man.writeToFile(ctx, (readLogContent(ctx) + "\r\n" + log.trim() + "\r\n").getBytes(), logFileName);			
		}
	}
	
	public static String readLogContent (Context ctx) {
		synchronized (mutex) {
			ReadWriteFileManager man = new ReadWriteFileManager();
			String str = man.readFromFile(ctx, logFileName);
			return str == null ? "" : str.trim(); 			
		}
	}
	
	public static boolean clearLogContent (Context ctx) {
		synchronized (mutex) {
			ReadWriteFileManager man = new ReadWriteFileManager();
			return man.writeToFile(ctx, "".getBytes(), logFileName);
		}
	}
	
}
